package cn.yikaojiuguo.student.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.adapter.GoldChargeAdapter;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.bean.GoldCharge;
import cn.yikaojiuguo.student.bean.MessageEvent;
import cn.yikaojiuguo.student.bean.PayResult;
import cn.yikaojiuguo.student.support.simple.UrlConstants;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.PayUtils;
import cn.yikaojiuguo.student.support.utils.RequestUtil;
import cn.yikaojiuguo.student.support.utils.ToastUtil;
import cn.yikaojiuguo.student.support.utils.ViewUtils;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.ui.base.CustomerActionBarActivity;

public class ChargeActivity extends CustomerActionBarActivity implements View.OnClickListener{

    @Bind(R.id.lv)
    ListView mLv;
    private GoldChargeAdapter mAdapter;
    private View mHeader;
    private View mFooter;
    private Button mBtn_ali;
    private Button mBtn_wx;
    private MyHandler mHandler = new MyHandler();

    public static Intent newIntent() {
        Intent intent = new Intent(YiKaoApplication.getInstance(), ChargeActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charge);
        ButterKnife.bind(this);
        initView();
        initEvents();
    }

    private void initView() {
        mHeader = View.inflate(this,R.layout.item_gold_charge_header,null);
        mFooter = View.inflate(this,R.layout.item_gold_charge_footer,null);
        mBtn_ali = ViewUtils.find(mFooter, R.id.btn_pay_ali);
        mBtn_wx = ViewUtils.find(mFooter,R.id.btn_pay_wx);
        mLv.addFooterView(mFooter);
        mLv.addHeaderView(mHeader);
    }

    private void initEvents() {
        getdata();
        mBtn_wx.setOnClickListener(this);
        mBtn_ali.setOnClickListener(this);
    }

    private void getdata() {
        showProgressDialog("正在加载...");
        String requestUrl = UrlConstants.GOLD_CHARGE_LIST;
        RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null && response.optBoolean("success")) {
                    dismissProgressDialog();
                    Gson gson = new Gson();
                    List<GoldCharge> list = gson.fromJson(response.optJSONArray("data").toString
                            (), new TypeToken<List<GoldCharge>>() {
                    }.getType());
                    mAdapter = new GoldChargeAdapter(ChargeActivity.this, list);
                    mLv.setAdapter(mAdapter);
                }
            }
        }, null, mTag);
    }

    @Override
    public void onClick(View v) {
        GoldCharge goldCharge;
        switch (v.getId()) {
            case R.id.btn_pay_ali:
                goldCharge = mAdapter.getChooseItem();
                if(goldCharge==null) {
                    ToastUtil.showToast(this,"请选择充值金额");
                    return;
                }
                setButtonsState(false);
                PayUtils.payByAli(this,goldCharge.id+"","金币","金币","0.01",mHandler);
                break;
            case R.id.btn_pay_wx:
                goldCharge = mAdapter.getChooseItem();
                if(goldCharge==null) {
                    ToastUtil.showToast(this,"请选择充值金额");
                    return;
                }
                setButtonsState(false);
                PayUtils.payByWx(this,goldCharge.id + "","0.01","金币");
                break;
        }
    }

    private void setButtonsState(boolean state) {
        mBtn_wx.setClickable(state);
        mBtn_ali.setClickable(state);
    }

    @Override
    public void onEvent(MessageEvent event) {
        super.onEvent(event);
        if(event.messageType == MessageEvent.MessageType.SHOW_PROGRESS_DIALOG) {
            showProgressDialog(event.message);
        } else if (event.messageType == MessageEvent.MessageType.BUTTON_PAY_ABLE) {
            setButtonsState(true);
        }
    }


    static class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            {
                switch (msg.what) {
                    case PayUtils.SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);
                        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                        String resultInfo = payResult.getResult();
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        Intent intent = null;
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.showToast(YiKaoApplication.getInstance(),"支付成功");
                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                ToastUtil.showToast(YiKaoApplication.getInstance(), "支付结果确认中");
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                ToastUtil.showToast(YiKaoApplication.getInstance(), "取消");
                            }
                        }
                        //EventBus.getDefault().post(new MessageEvent(MessageEvent.MessageType.ACTIVITY_FINISH));
                        break;
                    }
                    case PayUtils.SDK_CHECK_FLAG: {
                        LogUtil.showInfoLog("result = " + msg.obj);
                    }
                    break;
                    default:
                        break;
                }
            }
        }
    }

}
